package com.owc.common.sdk.client;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.owc.common.enums.ExceptionEnum;
import com.owc.common.exception.ParamDeficiencyException;
import com.owc.common.sdk.AbstractResponse;
import com.owc.common.sdk.Client;
import com.owc.common.sdk.request.Request;
import com.owc.common.sdk.util.HttpRequest;
import com.owc.common.sdk.util.ParserFactory;
import com.owc.common.tool.UtilsService;
import lombok.Getter;
import lombok.Setter;
import org.apache.log4j.Logger;

import java.lang.reflect.ParameterizedType;
import java.util.Map;

@Getter
@Setter
public class WalletClient implements Client {

    private static final Logger logger = Logger.getLogger(WalletClient.class);
    public static final String CHARSET_UTF8 = "UTF-8";
    private int connectTimeout;
    private int readTimeout;


    public WalletClient() {
        this.connectTimeout = 0;
        this.readTimeout = 0;
    }

    @Override
    public <T extends AbstractResponse> T execute(Request<T> request) throws Exception {

        String apiUrl = request.getApiUrl();

        if(UtilsService.isEmpty(apiUrl)){
            throw new ParamDeficiencyException(ExceptionEnum.CLIENT_INIT_ERR);
        }
        String responseMsg = "";
        try {
            switch (request.getMethod()){
                case "POST":
                    responseMsg = HttpRequest.sendPostRequest(apiUrl,(Map)request.getUrlParams(),request.getContentType());
                    break;
                case "GET":
                    responseMsg = HttpRequest.sendGetRequest(apiUrl);
                    break;
                default:
            }
            logger.info("Wallet response message json:" + responseMsg);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("【调用钱包api出现异常 url:{"+request.getApiUrl()+"} 报错文本:{"+e.getMessage()+"}】");
        }

        String jsonStr = machineJson(responseMsg,request);

        return this.parser(jsonStr,request.getResponseClass());
    }

    private String machineJson(String responseMsg,Request request) throws Exception {

        JSONObject resJson = JSON.parseObject(responseMsg);

        JSONObject jsonObject = new JSONObject();

        jsonObject.put("code",resJson.getIntValue("code"));
        jsonObject.put("success",resJson.getIntValue("code") == ExceptionEnum.SUCCESS.getCode());
        jsonObject.put("url",request.getApiUrl());
        jsonObject.put("message",resJson.getString("message"));
        jsonObject.put("resData",resJson.getString("resDate"));

        //获取泛型类
        Class cls;
        try {
            cls = (Class)((ParameterizedType)request.getResponseClass().getGenericSuperclass()).getActualTypeArguments()[0];
        } catch (Exception e) {
            throw new Exception(e);
        }
        jsonObject.put("data", JSON.parseObject(resJson.getString("data"),cls));
        return jsonObject.toJSONString();
    }

    private <T extends AbstractResponse> T parser(String responseMsg, Class<T> responseClass) throws Exception {
        return ParserFactory.JSON_PARSER.parse(responseMsg,responseClass);
    }
}
